const utils = {
  /**
   * 对象转url参数
   * @param {*} data
   * @param {*} isPrefix
   */
  queryParams(data, isPrefix = false) {
    let prefix = isPrefix ? "?" : "";
    let _result = [];
    for (let key in data) {
      let value = data[key];
      // 去掉为空的参数
      if (["", undefined, null].includes(value)) {
        continue;
      }
      if (value.constructor === Array) {
        value.forEach(_value => {
          _result.push(encodeURIComponent(key) + "[]=" + encodeURIComponent(_value));
        });
      } else {
        _result.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
      }
    }

    return _result.length ? prefix + _result.join("&") : "";
  },

  // 异常处理
  handleResult(res) {
    console.log("handleResult", res);
    if (res.status === 200) return extractResult(res.data);
    throw new Error(`HTTP请求错误[${res.status}] ${res.data}`);
  },
  extractResult({ success = false, message, data }) {
    console.log(success, message, data);
    if (success) return data;
    let reason = message || "未知错误";
    // if (code === 999) {
    //   reason = message || "未知错误";
    // } else if (code === -1001) {
    //   reason = "用户名或密码错误";
    // } else if (code === -1002) {
    //   reason = "用户不存在";
    // } else if (code === -1003) {
    //   reason = "用户未登录";
    // }
    throw new Error(reason);
  }

  // ....其他函数....
};

export default utils;
